package mx.com.crowdgine.display.animation.mocap;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AMCFile {
	
	private List<AMCFrame> amcFrames =  new ArrayList<AMCFrame>();
	private String rotationUnits;
	
	private String fileName;
	
	public AMCFile(String file) {
		this.fileName = file;
		parse();
	}
	
	private void parse() {
		try {
			BufferedReader in = new BufferedReader(new FileReader(fileName));
			
			String line = in.readLine();
			
			AMCFrame currentFrame = null;
			AMCBone currentBone = null;
			String [] frameValues = null;
			
			while(line != null) {
				
				if(!line.trim().startsWith("#")) {
					// ignore comments
					
					if(line.trim().startsWith(":FULLY-SPECIFIED")) {
						// ignore
					} else if(line.trim().startsWith(":DEGREES")) {
						rotationUnits = ":DEGREES";
					} else {
						if(isAllDigits(line.trim())) {
							// reading new frame
							currentFrame = new AMCFrame();
							this.amcFrames.add(currentFrame);
							currentFrame.setId(Integer.parseInt(line.trim()));
						} else {
							// reading bone definition
							frameValues = line.trim().split("\\s+");
							
							currentBone = new AMCBone();
							currentBone.setName(frameValues[0]);
							currentBone.setValues(new float[frameValues.length - 1]);
							
							for(int i = 1; i < frameValues.length; i++) {
								currentBone.getValues()[i-1] = Float.parseFloat(frameValues[i]);
							}
							
							currentFrame.getAmcBones().add(currentBone);
							
						}
					}
					
				}
				
				line = in.readLine();
			}
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private boolean isAllDigits(String line) {
		boolean allDigits = true;
		
		for(int i = 0; i < line.length(); i++) {
			if(!Character.isDigit(line.charAt(i))){
				allDigits = false;
				break;
			}
		}
		
		return allDigits;
	}

	public List<AMCFrame> getAmcFrames() {
		return amcFrames;
	}

	public void setAmcFrames(List<AMCFrame> amcFrames) {
		this.amcFrames = amcFrames;
	}

	public String getRotationUnits() {
		return rotationUnits;
	}

	public void setRotationUnits(String rotationUnits) {
		this.rotationUnits = rotationUnits;
	}
	
	
	
}
